use id date_q naicsq2 naicsq4 lmarkup* mshare* using ${dirTemp}/compustat_quarterly_markups, clear 

* Compute within-industry-quarter markup deviations and collapse to variance
* ==============================================================================
foreach m of varlist lmarkup* {
	forvalues k = 2(2)4 {
		gcollapse (mean) aux = `m', by(naicsq`k' date_q) merge 
		gen `m'_w`k' = `m' - aux 
		drop aux 
		gcollapse (sd) `m'_w`k'_sd = `m'_w`k', by(date_q) merge 
		gen `m'_w`k'_var = `m'_w`k'_sd^2
		drop `m'_w`k'_sd
		drop `m'_w`k'
	}
	drop `m' 
}

* Collapse log market shares to variance
* ==========================================
foreach m of varlist mshare* {
	gcollapse (sd) `m'_sd = `m', by(date_q) merge 
	gen `m'_var = `m'_sd^2
	drop `m'_sd 
	drop `m' 
}

* compute N of lmarkup_PF
* ===========================
gcollapse (count) N = lmarkup_PF_w2_var, by(date_q) merge
gen lmarkup_PF_logN=log(N)
drop N

* Make time series 
* ======================
bysort date_q: keep if _n == 1
drop id
drop naicsq* 
tsset date_q

* Add remaining macro data 
* ===============================
merge 1:1 date_q using ${dirTemp}/tsdata_macro, nogen 

* Save
* ==========

* Full period
save ${dirTemp}/tsdata_macromicro_long, replace

* Main Sample period
keep if date_quarterly >= yq(1995,1) & date_quarterly <= yq(2017,3)
save ${dirTemp}/tsdata_macromicro, replace
export delimited ${dirTemp}/tsdata_macromicro.csv, replace
